package vip.ola.pay.batchpay;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import vip.ola.core.common.util.MyLog;
import vip.ola.core.common.util.MySeq;
import vip.ola.core.common.util.PayDigestUtil;
import vip.ola.pay.ctrl.common.BaseController;
import vip.ola.pay.service.RpcCommonService;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.net.URI;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author: dingzhiwei
 * @date: 17/12/25
 * @description:
 */
@RequestMapping("/api/test")
@Controller
public class YousTransTestController extends BaseController {

    private static final MyLog _log = MyLog.getLog(YousTransTestController.class);
    @Autowired
    protected RpcCommonService rpcCommonService;

    @GetMapping("/dfTest")
    @ResponseBody
    public String trans(String amount,String bankName,String accountNo,String accountName) {
        String respData ="";
        try {
            String orderId = MySeq.getTrans();
            String payUrl = "http://a.qilin.store/api/pay/repay";
            TreeMap<String, String> obj = new TreeMap<String, String>();
            obj.put("name","张三");
            obj.put("ka", "6228489999999999999999");
            obj.put("money", "1");
            obj.put("merId", PaysUtil.memberCode);
            obj.put("bank", "中国工商银行");
            obj.put("nonceStr", "batch123");
            obj.put("notifyUrl", "http://159.138.11.127:8403/api/trans/notify");
            obj.put("orderId", orderId);
            // 生成签名
            StringBuffer paramstr = new StringBuffer();
            for (String pkey : obj.keySet()) {
                String pvalue = obj.get(pkey);
                if (pvalue != null && pvalue != "") {
                    paramstr.append(pkey + "=" + pvalue + "&");
                }
            }
            String paramsrc = paramstr.substring(0, paramstr.length() - 1);
            String sign = sign(paramsrc,PaysUtil.privateKey);
            String queryBytes = RSAUtils.sign(sign.getBytes("UTF-8"), PaysUtil.privateKey);
            obj.put("sign", queryBytes);
            _log.info("下单请求url={}，param={},json->{}",payUrl,obj,JSONObject.toJSONString(obj));
             respData = call(payUrl,obj);
            _log.info("下单结束respData->{}",respData);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  respData;
    }

    @GetMapping("/queryTest")
    @ResponseBody
    public JSONObject dfQuery(String merchantOrderNo) {
        JSONObject retObj = new JSONObject();
        retObj.put("transOrderId", merchantOrderNo);
        try {
            Map<String, String> obj = new HashMap<>();
            obj.put("merchantOrderNo", merchantOrderNo);
            String response=callGet("https://pay.fhpay.pro/order/cashierQuery",obj);
            _log.info("下单结束respData->{}",response);
            JSONObject jsonObject = JSONObject.parseObject(response);
            if (jsonObject != null){
                String code = jsonObject.getString("code");
                if ("200".equals(code)){
                    JSONObject dataObject =JSONObject.parseObject(jsonObject.getString("data"));
                    if (dataObject!= null && "1".equals(dataObject.getString("orderStatus"))){
                        retObj.put("status", 2);
                        retObj.put("channelOrderNo", jsonObject.getString("systemOrderNo"));
                    }else if (dataObject!= null && "0".equals(dataObject.getString("orderStatus"))){
                        retObj.put("status", 1);
                        retObj.put("channelOrderNo", jsonObject.getString("systemOrderNo"));
                    }else if (dataObject!= null && "2".equals(dataObject.getString("orderStatus"))){
                        retObj.put("status", 3);
                        retObj.put("channelOrderNo", jsonObject.getString("systemOrderNo"));
                    }else if (dataObject!= null && "3".equals(dataObject.getString("orderStatus"))){
                        retObj.put("status", 2);
                        retObj.put("channelOrderNo", jsonObject.getString("systemOrderNo"));
                    }else {
                        retObj.put("status", 1);
                        retObj.put("channelOrderNo", jsonObject.getString("systemOrderNo"));
                    }
                }else {
                    retObj.put("status", 1);
                    retObj.put("channelErrCode", code);
                    retObj.put("channelErrCode", jsonObject.getString("msg"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  retObj;
    }

    private static String sign(String paramSrc, String privateKey) {
        StringBuffer strbuff = new StringBuffer();
        strbuff.append(paramSrc + "&key=" + privateKey);
        String sign = null;
        try {
            sign = PayDigestUtil.md5(strbuff.toString(), "UTF-8").toUpperCase();
            _log.info("签名:" + sign);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return sign;
    }

    public  String callGet(String url, Map<String,String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            _log.info("请求参数："+uri.toString());
            HttpGet httpGet = new HttpGet(uri);

            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String call(String url, Map param) {
        CloseableHttpClient httpClient =HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        // 响应模型
        CloseableHttpResponse response = null;
        String responseContext = null;
        try {
            StringEntity entity = new StringEntity(JSONObject.toJSONString(param), ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            if (responseEntity != null) {
                responseContext = EntityUtils.toString(responseEntity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContext;
    }

    /**
     * 获取https连接（不验证证书）
     *
     * @return
     */
    private static CloseableHttpClient getHttpsClient() {
        RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.<ConnectionSocketFactory>create();
        ConnectionSocketFactory plainSF = new PlainConnectionSocketFactory();
        registryBuilder.register("http", plainSF);
        // 指定信任密钥存储对象和连接套接字工厂
        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            // 信任任何链接
            TrustStrategy anyTrustStrategy = new TrustStrategy() {

                @Override
                public boolean isTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException {
                    // TODO Auto-generated method stub
                    return true;
                }
            };
            SSLContext sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, anyTrustStrategy).build();
            LayeredConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            registryBuilder.register("https", sslSF);
        } catch (KeyStoreException e) {
            throw new RuntimeException(e);
        } catch (KeyManagementException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        Registry<ConnectionSocketFactory> registry = registryBuilder.build();
        // 设置连接管理器
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);
        // 构建客户端
        return HttpClientBuilder.create().setConnectionManager(connManager).build();
    }


    private String getSign(Map<String, String> map, String privateKey) {
        String param=map.get("merchantOrderNo")+map.get("appId")+map.get("channelCode")+map.get("payCode")+map.get("payFee")+privateKey;
        String sign = null;
        try {
            sign = PayDigestUtil.md5(param, "UTF-8");
            _log.info("签名:" + sign);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return sign;
    }


    public static void main (String args[]){
        String payeeName="李政 ";
        System.out.println(payeeName.length());
        System.out.println(payeeName.trim().length());
    }





}
